package tk.mybatis.springboot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * 测试依赖注入
 * 异步注解不生效问题 测试
 * <p>
 * 创建代理对象 方法
 * org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary(java.lang.Object, java.lang.String, java.lang.Object)
 * <p>
 * 问题点：为什么@lazy注入的就是代理对象
 * 为什么@PostConstruct 方法是在代理对象执行后执行的，但获取的bean却不是代理对象？
 *
 * @author liuzh
 * @since 2016-01-31 21:42
 */
@Slf4j
@Service
public class TestAsyncService extends AbstractProduce implements ApplicationContextAware, InitializingBean {


    private TestAsyncService testAsyncService;

    @PostConstruct
    public void init() {
        TestAsyncService bean = applicationContext.getBean(TestAsyncService.class);
        //testAsyncService = bean;
    }

    @Autowired
    public TestAsyncService(@Lazy TestAsyncService testAsyncService) {
        this.testAsyncService = testAsyncService;
    }


    @Override
    public void test() {
        System.out.println("======== test {}" + Thread.currentThread().getName());
        testAsyncService.testAsync();
    }

    @Async
    public void testAsync() {
        System.out.println("=========async test {}" + Thread.currentThread().getName());
        System.out.println("async lll");
    }


    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        TestAsyncService bean = applicationContext.getBean(TestAsyncService.class);
        //  testAsyncService = bean;
    }
}
